using System.Web.Http;
using Microsoft.Practices.Unity;
using TinCan.LRS.Web.Components;
using System.Web.Mvc;
using Unity.Mvc4;
using System.Configuration;
using Microsoft.Practices.Unity.Configuration;
using System.Reflection;
using System;

namespace TinCan.LRS.Web
{
    public static class Bootstrapper
    {
        public static void Initialise()
        {
            var container = BuildUnityContainer();

            DependencyResolver.SetResolver(new UnityDependencyResolver(container)); 

            GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
        }

        private static IUnityContainer BuildUnityContainer()
        {
            Uri UriAssemblyFolder = new Uri(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase));
            string appPath = UriAssemblyFolder.LocalPath;

            var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = System.IO.Path.Combine(appPath, "..\\config\\unity.config") };
            System.Configuration.Configuration configuration =
                ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            var unitySection = (UnityConfigurationSection)configuration.GetSection("unity");

            var container = new UnityContainer()
                .LoadConfiguration(unitySection);

            return container;
        }
    }
}